from django.shortcuts import render
from django.contrib.auth.hashers import make_password,check_password

# Create your views here.

from .models import *
from .ser import *
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
import re
from .ser import *

# class JournalismM(APIView):
#     def post(self,request):
#         datas = JournalismSer(data=request.data)
#         if datas.is_valid():
#             datas.save()
#             return Response({"code":200,"list":datas.data})
#         else:
#             print(datas.errors)
#             return Response({"code": 10010})
#     def get(self,request):
#         datas = Journalism.objects.all()
#         cpage = request.GET.get("cpage")
#
#         p = Paginator(datas,2)
#         stu = p.page(cpage)
#         ser = JournalismSer(stu,many=True)
#         return Response({"code":200,'list':ser.data,'tpage':p.num_pages})
#
# class AdvertisingM(APIView):
#     def post(self,request):
#         datas = AdvertisingSer(data=request.data)
#         print(request.data)
#         # return Response({"code":200})
#         if datas.is_valid():
#             datas.save()
#             return Response({"code":200,'list':datas.data})
#         else:
#             print(datas.errors)
#             return Response({"code":10010})

class ClassifyM(APIView):
    def get(self,request):
        datas = Classify.objects.all()
        ser = ClassifySer(datas,many=True)
        return Response({"code":200,'list':ser.data})

class show_ClassifyM(APIView):
    def get(self,request):
        id=request.GET.get('id')
        datas = Classify.objects.filter(id=id).first()
        ser = Show_ClassifySer(datas)
        return Response({"code":200,'list':ser.data})

class Reg(APIView):
    def post(self,request):
        #验证用户名
        name = request.data.get('username')
        #验证用户名是否为空
        if not name:
            return Response({"code":10010})
        #验证用户名是否合法
        reg = re.match("\w{5,10}$",name)
        if not reg:
            return Response({"code": 10011})
        #验证用户名唯一
        user = User.objects.filter(username=name).first()
        if user:
            return Response({"code":10012})

        # 验证密码
        password = request.data.get("password")
        if not password:
            return Response({"code": 10016})
        sreg = re.match("\w{5,20}$", password)
        if not sreg:
            return Response({"code": 10017})
        # return Response({"code": 200})


        #验证确认密码
        password1 = request.data.get("password1")
        if not password1:
            return Response({"code":10020})
        msg = re.match("\w{5,20}$", password1)
        if not msg:
            return Response({"code":10021})
        if password!=password1:
            return Response({"code":20022})

        # 验证手机号
        mobile = request.data.get("mobile")
        if not mobile:
            return Response({"code": 10013})
        mreg = re.match("^1[3-9]\d{9}$",mobile)
        if not mreg:
            return Response({"code":10014})
        mobiles = User.objects.filter(mobile=mobile).first()
        if mobiles:
            return Response({"code":10015})

        codesms = request.data.get('codesms')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code,encoding='utf8')
        if code != codesms:
            return Response({"code":10016})

        request.data['password']=make_password(password)
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            return Response({"code":10017})

        # return Response({'code':200})

import json
import random
from utils.comm import send_message,get_redis

class Test(APIView):
    def get(self,request):
        code = random.randint(100000,999999)
        result = send_message('17837733943',code,1)
        print(result)
        return Response('ok')

class SendSms(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        uid = request.data.get('uid')
        imgcode = request.data.get("imgcode")
        conn = get_redis()
        imgcodes = conn.get(uid)
        if imgcodes:
            imgcodes = str(imgcodes,encoding='utf8')
            if imgcodes.lower == imgcode.lower:
                code1 = random.randint(100000,999999),
                res = send_message(mobile,str(code1),1)
                code = 10010
                if res:
                    code=200
                    #发送验证码存入redis
                    conn = get_redis()
                    conn.setex(mobile,60,str(code1))
                return Response({"code":code})
        return Response({'code':10031})

# from django_redis import get_redis_connection
import redis
class Test1(APIView):
    def get(self,request):
        # conn=get_redis_connection()
        #字符串类型
        conn = get_redis()
        conn.set('username','xiaoming')
        name = conn.get('username')
        return Response(name)


from django.core.paginator import Paginator

from django_redis import get_redis_connection

from utils.captcha.captcha import captcha
from django.http import HttpResponse
class CreateCaptcha(APIView):
    def get(self,request):
        uuid = request.GET.get('uuid')
        print(uuid)
        name,text,img=captcha.generate_captcha()
        #redis存储
        conn = get_redis()
        conn.set(uuid,text)
        return HttpResponse(img,content_type="image/jpg")


#读取首页三级分类
class Home(APIView):
    def get(self,request):
        #读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list=[]
        for i in cates:
            dict={}
            dict['id'] = i.id
            dict['name'] = i.name
            #读取二级
            two = i.subs.all()
            print(two)
            twolist=[]
            #遍历二级获取三级
            for j in two:
                twodict={}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three,many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

            dict['subs'] = twolist
            list.append(dict)
        # return Response({"code":200,'catelist':list})
        # 查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的商品
        categoods = []
        for j in cates:
            dict = {}
            dict['id'] = j.id
            dict['name'] = j.name
            dict['pic'] = str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two, many=True)
            dict['two'] = twoser.data
            # 获取三级
            three = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(three, many=True)
            dict['three'] = threeser.data
            # 获取商品,排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')

            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()

            gser = GoodsSer(goods, many=True)
            dict['goods'] = gser.data
            categoods.append(dict)
        return Response({"code": 200, 'catelist': list, 'categoods': categoods})

class GoodsM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        good = Goods.objects.filter(id=id).first()
        ser = GoodsSer(good)
        return Response({"code": 200, 'good': ser.data})

